package com.sfh.appversion.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sfh.appversion.base.exception.ServiceException;
import com.sfh.appversion.dao.entity.*;
import com.sfh.appversion.dao.mapper.*;
import com.sfh.appversion.dto.req.AppEditReqDTO;
import com.sfh.appversion.dto.req.AppNewReqDTO;
import com.sfh.appversion.dto.resp.AppDowonSizeRespDTO;
import com.sfh.appversion.dto.resp.AppMenuRespDTO;
import com.sfh.appversion.server.AppServer;
import com.sfh.appversion.server.error.AppErrorCodeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.sfh.appversion.server.error.AppErrorCodeEnum.APP_UNKNOWN_ERROR;

@Slf4j
@Service
@RequiredArgsConstructor
public class AppServerImpl implements AppServer {

    private final AppInfoMapper appInfoMapper;
    private final AppVersionMapper appVersionMapper;
    private final AppVersionRecordMapper appVersionRecordMapper;
    private final PluginInfoMapper pluginInfoMapper;
    private final PluginVersionMapper pluginVersionMapper;

    @Override
    public List<AppMenuRespDTO> queryAllList(String appType) {
        List<AppMenuRespDTO> result = new ArrayList<>();
        LambdaQueryWrapper<AppInfoDO> queryWrapper = Wrappers.lambdaQuery(AppInfoDO.class)
                .eq(AppInfoDO::getAppType, appType)
                .orderByDesc(AppInfoDO::getAppSortTime);
        List<AppInfoDO> appInfoDOS = appInfoMapper.selectList(queryWrapper);
        if (appInfoDOS != null) {
            appInfoDOS.forEach(appInfoDO -> result.add(AppMenuRespDTO.create(appInfoDO)));
        }
        return result;
    }

    @Override
    public AppInfoDO queryInfo(String appId) {

        return appInfoMapper.selectById(appId);
    }

    @Override
    public String queryAppDownUrl(String appId) {
        return null;
    }

    @Override
    public AppDowonSizeRespDTO queryAppDownSize(String appId) {

        //全部下载量
        long allSize = appVersionRecordMapper.selectCount(Wrappers.lambdaQuery(AppVersionRecordDO.class)
                .eq(AppVersionRecordDO::getAppId, appId));
        //今日下载量
        Calendar calendar = Calendar.getInstance();
        // 获取当天的开始时间
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startTime = calendar.getTime();

        // 获取当天的结束时间
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endTime = calendar.getTime();

        long todaySize = appVersionRecordMapper.selectCount(Wrappers.lambdaQuery(AppVersionRecordDO.class)
                .eq(AppVersionRecordDO::getAppId, appId)
                .between(AppVersionRecordDO::getUpdateTime,startTime,endTime)
        );

        AppDowonSizeRespDTO dato =AppDowonSizeRespDTO.builder()
                .allSize(allSize)
                .todaySize(todaySize)
                .build();
        return dato;
    }

    @Override
    public boolean add(AppNewReqDTO vo) {
        LambdaQueryWrapper<AppInfoDO> queryWrapper =   Wrappers.lambdaQuery(AppInfoDO.class)
                .eq(AppInfoDO::getAppPackageName, vo.getAppPackageName());
        boolean exists = appInfoMapper.exists(queryWrapper);
        if (exists) {
            throw new ServiceException(AppErrorCodeEnum.APP_EXIST_ERROR);
        }

        AppInfoDO infoDO = AppInfoDO.builder()
                .appIcon(vo.getAppIcon())
                .appName(vo.getAppName())
                .appContent(vo.getAppContent())
                .appPackageName(vo.getAppPackageName())
                .appState(vo.getAppState())
                .appType(vo.getAppType()).build();
        return appInfoMapper.insert(infoDO) > 0;
    }

    @Override
    public boolean edit(AppEditReqDTO vo) {

        AppInfoDO appInfoDO = appInfoMapper.selectById(vo.getAppId());
        if (appInfoDO == null) {
            throw new ServiceException(APP_UNKNOWN_ERROR);
        }
        appInfoDO.setAppIcon(vo.getAppIcon());
        appInfoDO.setAppContent(vo.getAppContent());
        appInfoDO.setAppName(vo.getAppName());
        appInfoDO.setAppType(vo.getAppType());
        appInfoDO.setAppState(vo.getAppState());

        return appInfoMapper.updateById(appInfoDO) > 0;
    }


    @Override
    @Transactional
    public boolean del(String appId) {

        //删除版本
        appVersionMapper.delete(Wrappers.lambdaQuery(AppVersionDO.class)
                .eq(AppVersionDO::getAppId, appId));
        //删插件
        pluginInfoMapper.delete(Wrappers.lambdaQuery(PluginInfoDO.class)
                .eq(PluginInfoDO::getAppId, appId));
        //删插件版本
        pluginVersionMapper.delete(Wrappers.lambdaQuery(PluginVersionDO.class)
                .eq(PluginVersionDO::getAppId, appId));
        //删除应用
        return appInfoMapper.deleteById(appId) > 0;
    }

    @Override
    public boolean sortToFrist(String appId) {
        AppInfoDO appInfoDO = appInfoMapper.selectById(appId);
        if (appInfoDO == null) {
            throw new ServiceException(APP_UNKNOWN_ERROR);
        }
        appInfoDO.setAppSortTime(new Date());
        return appInfoMapper.updateById(appInfoDO) > 0;
    }
}
